export default class Snake {
  snake: HTMLElement;
  head: HTMLElement;
  bodys: HTMLCollection;
  constructor() {
    this.snake = document.getElementById("snake")!;
    this.head = this.snake.querySelector("div")!;
    this.bodys = this.snake.getElementsByTagName("div")!;
  }
  get X() {
    return this.head.offsetLeft;
  }
  get Y() {
    return this.head.offsetTop;
  }
  set X(value) {
    if (this.X === value) return;
    if (value < 0 || value > 290) throw new Error("撞墙了");
    if (this.bodys[1] && (this.bodys[1] as HTMLElement).offsetLeft === value) {
      console.log("掉头了");

      value = this.X > value ? this.X + 10 : this.X - 10;
    }
    this.moveBody();
    this.head.style.left = value + "px";
    this.touchBody();
  }
  set Y(value) {
    if (this.Y === value) return;
    if (value < 0 || value > 290) throw new Error("撞墙了");
    if (this.bodys[1] && (this.bodys[1] as HTMLElement).offsetTop === value) {
      console.log("掉头了");

      value = this.Y > value ? this.Y + 10 : this.Y - 10;
    }
    this.moveBody();
    this.head.style.top = value + "px";
    this.touchBody()
  }
  addBody() {
    this.snake.insertAdjacentHTML("beforeend", "<div></div>");
  }
  moveBody() {
    for (let i = this.bodys.length - 1; i > 0; i--) {
      const X = (this.bodys[i - 1] as HTMLElement).offsetLeft;
      const Y = (this.bodys[i - 1] as HTMLElement).offsetTop;
      (this.bodys[i] as HTMLElement).style.left = X + "px";
      (this.bodys[i] as HTMLElement).style.top = Y + "px";
    }
  }
  touchBody() {
    for (let i = 3; i < this.bodys.length; i++) {
      const element = this.bodys[i] as HTMLElement;
      if (element.offsetLeft === this.X && element.offsetTop === this.Y) {
        throw new Error("撞到自己了");
      }
    }
  }
}
